package apiserver

import (
	"encoding/json"

	apiv1 "gitee.com/youkelike/ziam/zapi/apiserver/v1"
	"gitee.com/youkelike/ziam/zsdk/sdk/request"
	"gitee.com/youkelike/ziam/zsdk/sdk/response"
)

type UserGetRequest struct {
	*request.BaseRequest
	Name string
}

func NewUserGetRequest() (req *UserGetRequest) {
	req = &UserGetRequest{
		BaseRequest: &request.BaseRequest{
			URL:     "/users/{Name}",
			Method:  "GET",
			Header:  nil,
			Version: "v1",
		},
	}
	return
}

type UserGetResponse struct {
	*response.BaseResponse
	apiv1.User
}

func NewUserGetResponse() *UserGetResponse {
	return &UserGetResponse{
		BaseResponse: &response.BaseResponse{},
	}
}

func (r *UserGetResponse) String() string {
	data, _ := json.Marshal(r.User)
	return string(data)
}

// 接口调用方法
func (c *Client) UserGet(req *UserGetRequest) (resp *UserGetResponse, err error) {
	resp = NewUserGetResponse()

	if req == nil {
		req = NewUserGetRequest()
	}

	// 这里如果这样用：
	// resp, err := c.send(req)
	// 那得到的 resp 也只能是一个通用的、 Response 接口的实例，不能直接当 UserGetResponse 用，
	// 相比之下，下面这种做法更巧妙
	err = c.Send(req, resp)
	if err != nil {
		return
	}

	if resp.Body != nil && len(resp.Body) > 0 {
		err = json.Unmarshal(resp.Body, &resp.User)
	}
	return
}
